#!/usr/bin/python
# coding=utf-8
import win32api
import win32con
import sys
import os
import hashlib

# 判断文件是否更改
def md5_modified_check(obj_path):
    old_md5 = ""
    if os.path.exists(obj_path + "\\topics_md5.dat"):  # md5文件存在，读取old_md5
        fmd5 = open(obj_path + "\\topics_md5.dat", 'r')
        old_md5 = fmd5.read()
        fmd5.close()

    # 遍历所有文件并提取msg文件
    str_msg = ""
    for root, dirs, files in os.walk(obj_path + "\\msg"):
        for name in files:
            if name.find('.msg') == -1:
                continue
            fpr = open(obj_path + "\\msg\\"+ name, 'r', encoding='utf-8')
            str_msg += fpr.read()
            fpr.close()
    new_md5 = hashlib.md5(str_msg.encode('utf-8')).hexdigest()
    # 比较md5值是否相等
    print("msg md5 check")
    print("old_md5:" + old_md5)
    print("new_md5:" + new_md5)
    if not old_md5 == new_md5: # 不相等则被更改
        fmd5 = open(obj_path + "\\topics_md5.dat", 'w')
        fmd5.truncate() #清空
        fmd5.write(new_md5) #写入新的md5
        fmd5.close()
        return True
    else:
        return False

# 名字对齐
def name_align(name, max_len):
    name_len = len(name)
    if name_len > max_len:
        win32api.MessageBox(0, "名字过长，最大限制为%d字符" % max_len, "提醒", win32con.MB_OK)
        exit(0)
    space_num = max_len - name_len + 1  # 至少加一个空格
    if space_num > 0:  # 用空格补齐len个字符长度
        i = 0
        while i < space_num:
            name += " "
            i += 1
    return name

# 打开h文件
def open_hfile(path, name):
    file = open(path + "\\" + name, 'w')
    # 清空
    file.truncate()
    # 写入注释头
    file.write("\
/*---------------------------------------------------------------------\n\
 * File name:" + name + "\n\
 *\n\
 * Copyright (c) <2020-2022>, <ChenLong>\n\
 *\n\
 * All rights reserved.\n\
 *\n\
 * Author: ChenLong\n\
 * Email: worldlong@foxmail.com\n\
 *--------------------------------------------------------------------*/\n")
    file.write("#pragma once\n")
    file.write("/*\n*/\n")
    file.write("typedef struct\n")
    file.write("{\n")
    return file

# 关闭h文件
def close_hfile(fp, name, id):
    var_name = "topic_" + name.replace(".msg", "_t")
    fp.write("}" + var_name + ";\n")
    fp.write("/*\n*/\n")
    def_name = var_name[:-2]
    id_name = def_name.upper() + "_ID"
    str_def = "#define " + id_name
    str_def = name_align(str_def, 30) + str(id) + "\n"
    fp.write(str_def)
    str_def = "#define " + def_name.upper() + "_SIZE"
    str_def = name_align(str_def, 30) + "sizeof(" + var_name + ")\n"
    fp.write(str_def)
    fp.close()

# 程序开始
obj_path = sys.argv[1]
if not md5_modified_check(obj_path):
    print("no change")
   # exit(0)

# 全局变量
topic_id = 0
# 遍历所有文件并提取msg文件
msg_path = obj_path + "\\msg"
for root, dirs, files in os.walk(msg_path):
    for name in files:
        if name.find('.msg') == -1:
            continue
        hfile_name = "topic_" + name.replace(".msg", ".h")
        fpw = open_hfile(obj_path, hfile_name)
        fpr = open(msg_path + "\\" + name, 'r', encoding='utf-8')
        for line in fpr.readlines():
            if line.startswith("#"):  # 生成注释
                fpw.write(line.replace("#", "//"))
            elif line.startswith("\n"):  # 直接换行
                fpw.write(line)
            elif not line.startswith(" "):
                str_list = line.split('#')
                def_list = str_list[0].split(' ')
                if len(def_list) < 2:
                    win32api.MessageBox(0, "msg定义错误", "提醒", win32con.MB_OK)
                    exit(0)
                var_name = def_list[1].replace(' ', '');
                var_name = def_list[1].replace('\n', '');
                var_def = def_list[0] + ' ' + var_name + ";"
                var_def = name_align(name=var_def, max_len=30)
                if len(str_list) > 1:
                    var_def += "   //" + str_list[1].replace('\n', '')
                fpw.write("  " + var_def + "\n")
        close_hfile(fpw, name, topic_id);
        topic_id += 1
        fpr.close()
print("end")
exit(0)
